/***
 * 防抖 只触发最后一次
 *  @param {Function} fn - 执行事件(函数)
 *  @param {?String|"click"} event - 事件类型 例："click","input"
 *  @param {?Number|300} time - 间隔时间
 *
 *  例：<el-button v-debounce="[reset,`click`,300]">刷新</el-button>
 *  也可简写成：<el-button v-debounce="[reset]">刷新</el-button>
 *  例：<el-input v-debounce="[reset,`input`,300]"></el-input>
 */
module.exports = {
  //  1.(钩子函数) 当被绑定的元素插入到 DOM 中时   类似于组件的 created
  bind(el, binding) {
    console.log(el);
    console.log(binding);
  },

  // 2.(钩子函数) 当被绑定的元素插入到 DOM 中时   类似于组件的 mounted
  inserted: function (el, binding) {
    let [fn, event = 'click', time = 300] = binding.value;

    let timer;
    let flag = true; //输入法标记
    if (event === 'input') {
      el.addEventListener('compositionstart', () => {
        flag = false;
      });
      el.addEventListener('compositionend', () => {
        flag = true;
      });
    }
    el.addEventListener(event, () => {
      timer && clearTimeout(timer);
      timer = setTimeout(() => {
        if (flag) fn();
      }, time);
    });
  },
};
